package com.ruoyi.api.api;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.api.domain.GaodeMap;
import org.springframework.stereotype.Component;

/**
 * 高德地图获取经纬度Api
 *
 * @author 寻觅
 * @since 2025-05-26
 */
@Component
public class GaodeMapAPI {

    private static final String API_KEY = "f6a20ff6b2eea9122f5c0a15411a513c";
    private static final String GEOCODING_URL = "https://restapi.amap.com/v3/geocode/geo";

    /**
     * 根据地址获取经纬度
     * @param address 地址，如：北京市海淀区中关村
     * @return 包含经纬度的JSON对象，出错时返回null
     */
    public static JSONObject getLocation(String address) {
        try {
            // 编码地址参数
            String encodedAddress = URLEncoder.encode(address, "UTF-8");
            // 构建请求URL
            String requestUrl = String.format("%s?key=%s&address=%s",
                    GEOCODING_URL, API_KEY, encodedAddress);

            // 发送HTTP请求
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 读取响应
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 解析JSON响应
            JSONObject result = JSONObject.parseObject(response.toString());
            if ("1".equals(result.getString("status")) && result.getIntValue("count") > 0) {
                // 提取经纬度（格式：经度,纬度）
                JSONObject geocode = result.getJSONArray("geocodes").getJSONObject(0);
                return geocode;
            } else {
                System.err.println("获取经纬度失败: " + result.getString("info"));
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        // 示例：获取"天津市滨海国际机场"的经纬度
        JSONObject location = getLocation("哈哈哈哈");
        if (location != null) {
            String locationStr = location.getString("location");
            System.out.println("天津市滨海国际机场的经纬度: " + locationStr);
            // 分割经纬度
            String[] lngLat = locationStr.split(",");
            System.out.println("经度: " + lngLat[0]);
            System.out.println("纬度: " + lngLat[1]);
        }
    }

    public GaodeMap getLandmark(String landmark){
        JSONObject location = getLocation(landmark);
        GaodeMap gaodeMap = new GaodeMap();
        if (location != null) {
            String locationStr = location.getString("location");
            // 分割经纬度
            String[] lngLat = locationStr.split(",");
            System.out.println("经度: " + lngLat[0]);
            System.out.println("纬度: " + lngLat[1]);

            gaodeMap.setLatitude(lngLat[0]);
            gaodeMap.setLongitude(lngLat[1]);
        }
        return gaodeMap;
    }


}
